import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Form, Input, Select, Avatar, Button, Upload, Icon, message,Checkbox } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import api from "../../../api/api";
import axios from 'axios';
import lodash from 'lodash'
// import { Upload, message, Button, Icon } from 'antd';
const { Option } = Select;
const FormItem = Form.Item;


function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('请选择png或者jpg图片');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2M');
  }
  return isJpgOrPng && isLt2M;
}

@Form.create()
class Model extends React.Component {

  formRef = React.createRef()
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      identityFlagPerson:"",
      hiddenFlag:true,
      visible: false,
      logoImageUrl: '',
      intervalObj: Object,
      factorySelectDataInitFlag: false,
      departmentSelectDataInitFlag: false,
      intervalCount: 0,
      selectCompanyId: undefined,
      selectFactoryId: undefined,
      selectDepartmentId: undefined,
      param: {
        gh:"",
        userId: "",
        logo: "",
        gid: "",
        gname:"",
        cqName: "",
        cqId:"",
        deptCode:"",
        deptName: "",
        sex: "",
        phone: "",
        name: "",
        identityFlag: "",
        orgCode: "",
        identityFlagPerson:""
      }
    };
  }
  componentDidMount() {
    this.clearData()
    this.props.onRef(this)
    this.companyChange();

    console.log("dialog初始化==", this.props);
  }
  componentWillUnmount(){
    clearInterval(this.state.intervalObj)
  }
//确定
  handleOk = () => {
    this.props.form.validateFields((error, values) => {
      console.info("values=========", values);
      if (error != null) {
        return;
      }else{
        const that = this;
          let {param} = this.state
        if (values.identityFlag=="普通用户") {
          values.identityFlag=0
        }else if(values.identityFlag=="审核人员"){
          values.identityFlag=2
        }else if(values.identityFlag=="门岗") {
          values.identityFlag=1
        }

        if (values.identityFlagPerson=="室主任/作业长") {
          values.identityFlagPerson=1
        }else if (values.identityFlagPerson=="部门长") {
          values.identityFlagPerson=2
        }else if (values.identityFlagPerson=="公司领导") {
          values.identityFlagPerson=3
        }else if (values.identityFlagPerson=="访问审核") {
          values.identityFlagPerson=4
        }

        console.log("values",values)
          if ( values.identityFlag==2 && values.identityFlagPerson==="") {
            alert("请选择审核人员")
          }else{
            param.gh = values.gh
            param.identityFlag = values.identityFlag
            param.logo = this.state.logoImageUrl;
            param.sex = values.sex
            param.phone = values.phone
            param.name = values.name
            param.gid = values.gid
            param.cqId = values.cqId
            param.deptCode = values.deptCode
            param.orgCode = localStorage.getItem("orgCode")
            param.identityFlagPerson=values.identityFlagPerson
            this.setState({param}, () => {
              console.log(this.state.param)
              this.personData()
            })
          }
      }
    })
  }

  //添加，编辑请求提交
  personData() {
    console.log(this.state.param)
    let url = ""
    if(this.props.data.type === 2) {  //编辑
      url = api.api_URL + "/admin/visituserinfo/updateVisitUserInfo"
      let { param } = this.state
      param.userId = this.props.data.gridList.userId
      this.setState({ param }, () => {
        this.addUser(url)
      })
    }else {                         //添加
      url = api.api_URL + "/admin/visituserinfo/addVisitUserInfo"
      if(this.props.data.type === 1) {
        this.addUser(url)
      }else{
        let { param } = this.state
        param.userId = this.props.data.gridList.userId
        this.setState({ param }, () => {
          this.addUser(url)
        })
      }
    }
    this.setState({
      identityFlagPerson:undefined
    })

  }


  //初始化编辑数据
  initEditData = () => {
    let that = this;
    const {param} = this.state;
    param.gname=this.props.data.gridList.gname;
    param.deptName=this.props.data.gridList.deptName;
    param.cqName=this.props.data.gridList.cqName;
    that.setState({
       logoImageUrl: this.props.data.gridList.logo
    })
    console.log(this.state.param)
    this.factoryChange(this.props.data.gridList.cqId); //厂区下拉框数据
    this.state.intervalObj = setInterval(function () {
      that.setBaseInfo()
    },100)

  }
  //编辑的初始值设置
  setBaseInfo(){
    let that = this;
    let data = this.props.data.gridList
    if(data.identityFlag=="审核人员"){
      that.setState({
        hiddenFlag: false,
        c1:"0"
      })
    }
console.log(that.state.c1)
    // if(data.identityFlagPerson==0){
    //   that.setState({
    //     identityFlagPersonOption:[{label:"访问审核人员",value:0},{label:"放行审核人员",value:1}],
    //   })
    // }else if(data.identityFlagPerson==1){
    //   that.setState({
    //     identityFlagPersonOption:[{label:"访问审核人员",value:1},{label:"放行审核人员",value:0}],
    //   })
    // }else if(data.identityFlagPerson==10){
    //   that.setState({
    //     identityFlagPersonOption:[{label:"访问审核人员",value:0},{label:"放行审核人员",value:0}],
    //   })
    // }
    const { form } = this.props;
    if ((this.state.factorySelectDataInitFlag && this.state.departmentSelectDataInitFlag) || this.state.intervalCount >= 9){
      this.state.factorySelectDataInitFlag = false;
      this.state.departmentSelectDataInitFlag = false;
      clearInterval(this.state.intervalObj)
      Object.keys(form.getFieldsValue()).forEach(key => {
        const obj = {};
        if (data[key]) {
          obj[key] = data[key] || null;
        }
        form.setFieldsValue(obj);
      });
    }else{
      this.setState({
        intervalCount:this.state.intervalCount + 1
      })
    }

  }
  //添加
  addUser(url){
    const that = this;
    console.log(this.state.param)
    axios({
      method: 'POST',
      url: url,
      data: JSON.stringify(this.state.param),
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": "application/json;charset=UTF-8"
      },
    }).then(function (response) {
      that.handleCancel()
      message.success({content:"成功！"})

    }).catch(function (error) {
      message.error({content:"失败！"})
      console.log(error);
     })
  }
  handleCancel = e => {
    this.clearData()
    this.props.handleCancel()
  };
 //公司下拉框
  companySelect=[];
  getCompanySelect(){
    let that = this;
    let dataList = [];
    let url = api.api_URL+"/admin/company/queryAllCompanyInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
    axios.get(url, {
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": api.ContentType
      }
    }).then(function (res) {
      if (res.data.code != 1) {
        alert(res.data.msg);
        return;
      }
      let companyInfoList = res.data.data.companyInfoList;
      for (let i = 0; i < companyInfoList.length; i++) {
        let comData = companyInfoList[i];
        const data = {};
        data.key = comData.thirdCompanyId;
        data.label = comData.companyName;
        dataList[i] = data;
      }
      for (let i = 0; i < dataList.length; i++) {
        that.companySelect.push(<Option key={dataList[i].key} value={dataList[i].key}>{dataList[i].label}</Option>);
      }

    }).catch(function (err) {
      console.log(err);
    })
  }
  //选择公司
  companyChange=()=> {

      this.props.form.resetFields('deptCode',[]);
      this.departmentSelect = [];
    this.props.form.resetFields('cqId',[]);
    this.props.form.resetFields('deptCode',[]);
    this.factorySelect = [];
    this.departmentSelect = [];
    let that = this;
    let dataList = [];
    let url;
    url = api.api_URL+"/admin/factory/queryFactoryInfoForSelect?orgCode="+localStorage.getItem('orgCode');
    axios.get(url, {
      headers: {
        "Authorization": localStorage.getItem('token'),
        "Content-Type": api.ContentType
      }
    }).then(function (res) {
      if (res.data.code != 1) {
        alert(res.data.msg);
        return;
      }
      let factoryInfoList = res.data.data.factoryInfoList;
      if(factoryInfoList.length <=0){
        console.log("没有厂房数据")
      //  this.factorySelect.push(<Option key="">没有厂房数据</Option>);
        return;
      }
      for (let i = 0; i < factoryInfoList.length; i++) {
        let facData = factoryInfoList[i];
        const data = {};
        data.key = facData.thirdFactoryId;
        data.label = facData.name;
        dataList[i] = data;
      }
      for (let i = 0; i < dataList.length; i++) {
        that.factorySelect.push(<Option key={dataList[i].key} value={dataList[i].key}>{dataList[i].label}</Option>);
      }
      that.setState({
        factorySelectDataInitFlag: true
      })
    }).catch(function (err) {
      console.log(err);
    })

  }

  //选择厂区
  factoryChange=(value)=> {
    this.setState({
      selectFactoryId: value
    })
    let {param} = this.state
    param.cqId= value
      this.setState({
        selectFactoryId: value
      })
      this.props.form.resetFields('deptCode',[]);
      this.departmentSelect = [];
      let that = this;
      let dataList = [];
      console.log(value)
      let url = api.api_URL + "/admin/dept/queryAllDepartmentInfoByThirdFactoryIdForSelect?thirdFactoryId=" + value + "&orgCode=" + localStorage.getItem('orgCode');
      axios.get(url, {
        headers: {
          "Authorization": localStorage.getItem('token'),
          "Content-Type": api.ContentType
        }
      }).then(function (res) {
        if (res.data.code != 1) {
          return;
        }
        console.log(res.data.data)
        let departmentInfoList = res.data.data.departmentInfoList;
        if (departmentInfoList.length <= 0) {
          console.log("没有部门数据")
          return;
        }
        for (let i = 0; i < departmentInfoList.length; i++) {
          let comData = departmentInfoList[i];
          const data = {};
          data.key = comData.code;
          data.label = comData.name;
          console.log(data)
          dataList[i] = data;
        }
        console.log(("factoryChange:" + dataList))
        for (let i = 0; i < dataList.length; i++) {
          that.departmentSelect.push(<Option key={dataList[i].key} value={dataList[i].key} >{dataList[i].label}</Option>);
        }
        that.setState({
          departmentSelectDataInitFlag: true
        })
      }).catch(function (err) {
        console.log(err);
      })
   }

    identityFlagChange =(value)=> {
    let that=this;
      if (value==2||value=="2"){
        that.setState({
          hiddenFlag: false
        })
      }else {
        that.setState({
          hiddenFlag: true
        })
      }
    }
//   identityFlagPersonChange=(value)=> {
//
//     console.log(value);
//     let that = this;
//     if (value=="访问审核人员"){
//       this.setState({
//         identityFlagPerson:0
//       })
//     }else if(value=="放行审核人员"){
//       this.setState({
//         identityFlagPerson:1,
//       })
//     }else if(value==("访问审核人员,放行审核人员")||value==("放行审核人员,访问审核人员")) {
//       this.setState({
//         identityFlagPerson:10
//       })
//     }else{
//       this.setState({
//         identityFlagPerson: "5"
//       })
//   }
// }

  departmentChange=(value)=> {
    this.setState({
      selectDepartmentId: value
    })
    let {param} = this.state
    param.deptCode= value
    }


  //清空form表单数据
  clearData() {
    this.props.form.resetFields();
    this.setState({
      gname:"",
      deptName:"",
      cqName:"",
      logoImageUrl:"",
      userId:"",
      hiddenFlag: true
    })
  }

  handleAvatarChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      console.log("handleAvatarChange===",info)
      this.setState({
        logoImageUrl: info.file.response.data.filename,
        loading: false,
      })
    }
  };

  render() {
    const { getFieldDecorator, getFieldError } = this.props.form
    const { logoImageUrl } = this.state;
    const CheckboxGroup = Checkbox.Group;
    const uploadButton = (
        <div>
          {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div className="ant-upload-text">上传头像</div>
        </div>
    );
    return (
      <div>
        <Modal
          title={this.props.data.title}
          visible={this.props.data.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form name="control-ref"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            layout="horizontal"
          >
            <FormItem  label="工号" name="gh"  allowClear >
              {getFieldDecorator("gh", {
                rules: [{ required: true, message: '工号不可缺！' } ,
                ],
              })(
                  <Input
                      maxLength={32}
                      placeholder="请输入工号"
                  />
              )}

            </FormItem>
            <FormItem label="头像" name="logo" >
              <Upload
                  name="logo"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  action={api.api_URL + "/admin/fileupload/uploadLogo"}
                  beforeUpload={beforeUpload}
                  onChange={this.handleAvatarChange}
              >
                {logoImageUrl ? <img src={api.api_URL + "/admin/fileupload/getIDCardStream?urlPath=" + logoImageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>
            </FormItem>
            <FormItem  label="姓名" name="name" >
              {getFieldDecorator("name", {})(
                  <Input />
              )}
            </FormItem>
            <FormItem label="性别"  name="sex">
              {getFieldDecorator("sex", {
                initialValue: "男"
              })(
                    <Select>
                    <Option key="男">男</Option>
                    <Option key="女">女</Option>
                  </Select>
              )}

            </FormItem>
            <FormItem   label="手机号" name="phone" >
              {getFieldDecorator("phone", {
              rules: [{ required: true, message: '请填写客户电话!',whitespace: true,}] ,
              })(
                  <Input />
              )}
            </FormItem>

            <FormItem  label="所属公司" name="cqId">
              {getFieldDecorator("cqId", {
              })(
                  <Select showSearch={true} optionFilterProp="children"  placeholder="请选择公司" onChange={this.factoryChange}  allowClear >
                    {this.factorySelect}
                  </Select>
              )}
            </FormItem>

            <FormItem  label="所属部门" name="deptCode">
              {getFieldDecorator("deptCode", {
              })(
                  <Select showSearch={true} optionFilterProp="children" placeholder="请选择部门" onChange={this.departmentChange}  allowClear >
                    {this.departmentSelect}
                  </Select>
              )}
            </FormItem>
            <FormItem  label="身份" name="identityFlag">
              {getFieldDecorator("identityFlag", {
                initialValue: "1"
              })(
                  <Select onChange={this.identityFlagChange} >
                    <Option key="0">普通用户</Option>
                    <Option key="1">门岗</Option>
                    <Option key="2">审核人员</Option>
                  </Select>
              )}
            </FormItem>
            <FormItem  label="角色" name="identityFlagPerson" hidden={this.state.hiddenFlag}  >
              {getFieldDecorator("identityFlagPerson", {
                initialValue: "1"
              })(
                  <Select>
                    <Option key="1">室主任/作业长</Option>
                    <Option key="2">部门长</Option>
                    <Option key="3">公司领导</Option>
                    <Option key="4">访问审核</Option>
                  </Select>
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
Model.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}
export default Model
